import React from 'react';
import {connect} from 'react-redux'
import config from 'config';
import menuRoute from 'routes/menuRoute'
import {Table, Button, Popover, Form, Modal, Radio, Input, Row, Col, Icon, Upload, message, Select, Tabs, Switch
} from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const TabPane = Tabs.TabPane;
const Option = Select.Option;
import BasicInfo from 'components/basic-info';
import chooserData from "share/chooserData";
import ListSelector from 'components/list-selector.js';
import {messages} from "share/common";
import LanguageInput from 'components/template/language-input/language-input';
import subApplicationService from 'containers/setting/sub-application/sub-application.service'
import configureStore from "stores";
import ResizeTable from "components/resize-table";

class SubApplicationVersionRecordDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      syncLoading: false,
      data: [],
      page: 0,
      pagination: {
        total: 0,
        showQuickJumper: true,
      },
      columns: [],
      tenantColumns: [
        {
          title: messages('setting.key2058')/*租户名称*/, dataIndex: 'tenantName', render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key2059')/*租户ID*/, dataIndex: 'id', render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
      ],
      userColumns: [
        {
          title: messages('setting.key1213')/*姓名*/, dataIndex: 'fullName', render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key2060')/*手机号*/, dataIndex: 'mobile', render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key1216')/*部门名称*/, dataIndex: 'departmentName', render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
        {
          title: messages('setting.key33')/*职务*/, dataIndex: 'title', render: (text) => {
            return (
              <Popover content={text}
                       placement={'topLeft'}
                       overlayClassName={'tenant-maintenance-popover'}
                       overlayStyle={{whiteSpace: 'pre-wrap', maxWidth: 350}}>
                <div>{text}</div>
              </Popover>
            )
          }
        },
      ],
      selectedRowKeys: [],
      selectorItemStaff: chooserData['user'],//选择人员弹窗显示配置
      showListSelectorStaff: false,//人员弹窗是否显示
      infoList: [
        {
          type: 'input',
          label: messages('setting.key1026')/*应用名称*/,
          id: 'appName',
          disabled: true
        },
        {
          type: 'switch',
          label: messages('setting.key1096')/*状态*/,
          id: 'enabled',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key2061')/*强制更新*/,
          id: '_mandatory',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key1971')/*版本号*/,
          id: 'appLevel',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key2062')/*主版本号*/,
          id: 'appMainVersion',
          disabled: true
        },

        {
          type: 'input',
          label: messages('setting.key2063')/*操作系统*/,
          id: 'platform',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key2064')/*版本描述*/,
          id: 'releaseNote',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key2065')/*代码资源*/,
          id: 'downloadLink'
        },
      ],
      infoData: {},//当前版本详情数据
      visible: false,
      id: props.params.id,
      appCode: props.params.code,
      appLevel: props.location.state.appLevel,
      appName: props.location.state.appName,
      fileList: [],//资源文件
      scope: true,//适用范围是否为全部
      activeKey: 'user',
      subApplicationData: {
        appName: "",//名称
        i18n: {}//包含名称,描述
      },
      versionOptions: [],
      subApplicationInfo: menuRoute.getRouteItem('edit-sub-application-privatization', 'key').url,
    }
  }

  componentWillMount() {
    this.getSubApplicationVersionDetail();
  }

  //获取版本详情
  getSubApplicationVersionDetail = () => {
    const {id, fileList} = this.state;
     subApplicationService.getVersionRecord(id).then(res => {
        if (!fileList.length) {
          let item = {uid: 0, fileUrl: res.data.downloadLink, name: res.data.downloadLink};
          fileList.addIfNotExist(item);
        }
        res.data.appName = this.state.appName;
        res.data._mandatory = res.data.mandatory ? messages('setting.key1393')/*是*/ : messages('setting.key1394')/*否*/;
        this.setState({
          infoData: res.data,
          scope: res.data.isPublic,
          fileList,
        }, () => {
          if (!this.state.scope) {
            this.updateTable();
          }
        })
      }
    ).catch(err => {

    })
  };

  //获取子应用版本用户权限
  getSubVersionUserLimit = () => {
    const {page, id, userColumns} = this.state;
    this.setState({
      loading: true,
      columns: userColumns,
    });
     subApplicationService.getSubVersionUserLimit(id, page).then(res => {
      if (res.status === 200) {
        this.setState({
          data: res.data,
          loading: false,
          pagination: {
            total: Number(res.headers['x-total-count']),
            onChange: this.onUserChangePaper,
            current: this.state.page + 1
          }
        })
      }
    }).catch(err => {
      this.setState({
        loading: false,
      });
    });
  };

  //获取最小版本选项
  getVersionOptions = () => {
    const {appCode} = this.state;
     subApplicationService.getVersionOptions(appCode, '').then(res => {
      this.setState({
        versionOptions: res.data,
      })
    }).catch(err => {

    })
  };

  onUserChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({
        page: page - 1,
      }, () => {
        this.getSubVersionUserLimit();
      });
    }
  };

  onSelectChange = (selectedRowKeys) => {
    this.setState({
      selectedRowKeys: selectedRowKeys,
    });
    let arr = [];
    selectedRowKeys.map(item => {
      arr.addIfNotExist(JSON.parse(item))
    });
  };

  // 选择人员的弹窗
  getStaffModal = () => {
    this.setState({showListSelectorStaff: true});
  };

  //人员
  handleStaffListOk = (result) => {
    let arr = [];
    result.result.map(item => {
      arr.addIfNotExist({userId: item.id})
    });
    this.addSubVersionLimits(arr, false);
    this.handleStaffCancel();
  };

  //人员
  handleStaffCancel = () => {
    this.setState({showListSelectorStaff: false,})
  };

  //添加人员或租户权限
  addSubVersionLimits = (arr, bool) => {
    const {infoData} = this.state;
    this.setState({
      loading: true,
    });
    infoData.widgetVersionRelationList = arr;
    infoData.isPublic = bool;
     subApplicationService.addSubApplicationLimit(infoData).then(res => {
      this.setState({
        loading: false,
      });
      this.updateTable();
    }).catch(err => {
      this.setState({
        loading: false,
      });
    });

  };

  //点击删除
  handleDelete = () => {
    const {id, selectedRowKeys} = this.state;
    this.setState({
      loading: true,
    });
    let arr = [];
    selectedRowKeys.map(item => {
      arr.addIfNotExist(JSON.parse(item))
    });
     subApplicationService.deleteSubApplicationLimit(id, arr).then(res => {
      this.setState({
        loading: false,
      });
      this.updateTable();
    }).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  //上传文件时
  handleUploadChange = (file) => {
    this.setState({
      fileList: file.fileList,
    })
  };

  //编辑完保存
  onModalOk = () => {
    const {fileList, infoData} = this.state;
    if (!fileList.length) {
      message.error(messages('setting.key2066')/*请上传代码资源*/)
    } else {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.setState({
            loading: true,
          });
          values.downloadLink = fileList[0].fileUrl || fileList[0].response.path;
          let params = Object.assign(infoData, values);
           subApplicationService.editVersionRecord(params).then(res => {
            this.setState({
              visible: false,
              loading: false,
            });
            this.getSubApplicationVersionDetail();
            message.success(messages('setting.key211')/*保存成功*/)
          }).catch(err => {
            this.setState({
              loading: false,
            })
          });
        }
      });
    }
  };

  //编辑完取消
  onModalCancel = () => {
    this.props.form.resetFields();
    this.setState({
      visible: false,
    })
  };

  //适用范围选择全部时
  confirmAll = () => {
    let that = this;
    Modal.confirm({
      title: messages('setting.key2067')/*选择全部适用后会清空之前的适用范围*/,
      okText: messages('setting.key1484')/*确认*/,
      cancelText: messages('setting.key1080')/*取消*/,
      iconType: 'info-circle',
      onOk() {
        that.setState({
          scope: true,
          page: 0,
          selectedRowKeys: [],
        });
        that.isPublicChange(true);
      },
      onCancel() {
      },
    });
  };

  //适用范围选择部分时
  confirmPart = () => {
    Modal.confirm({
      title: messages('setting.key2068')/*选择部分适用后会清空之前的适用范围*/,
      okText: messages('setting.key1484')/*确认*/,
      cancelText: messages('setting.key1080')/*取消*/,
      iconType: 'info-circle',
      onOk: () => {
        this.setState({
          scope: false,
          page: 0,
          selectedRowKeys: [],
        });
        this.isPublicChange(false);
      },
      onCancel() {
      },
    });
  };

  //适用范围变更
  isPublicChange = (bool) => {
    if (bool) {
      this.addSubVersionLimits([], true);
    } else {
      this.setState({
        showListSelectorStaff: true,
      });
    }
  };

  //跳转到子应用详情编辑页
  goSubApplicationDetail = () => {
    const {subApplicationInfo, appCode, appName, id} = this.state;
    this.context.router.push({
      pathname: subApplicationInfo.replace(":code", appCode),
      state: {
        id: id,
        code: appCode,
        appName: appName,
        tab: 'version_record'
      }
    });
  };

  //适用范围变化时
  onRadioGroupChange = (e) => {
    if (e.target.value) {
      this.confirmAll();
    } else {
      this.confirmPart();
      this.updateTable();
    }
  };

  //根据适用范围更新表格
  updateTable = () => {
    this.setState({
      page: 0,
      selectedRowKeys: [],
    });
    this.getSubVersionUserLimit();
  };

  //版本描述多语言
  i18nNameChange = (name, i18nName) => {
    this.state.infoData.releaseNote = name;
    if (this.state.infoData.i18n) {
      this.state.infoData.i18n.releaseNote = i18nName;
    } else {
      this.state.infoData.i18n = {
        releaseNote: i18nName
      };
    }
  };

  render() {
    const {
      pagination, data, columns, loading, selectedRowKeys, showListSelectorStaff, selectorItemStaff,
      infoList, infoData, appName, appLevel, visible, fileList, showListSelector, selectorItem, scope,
      activeKey, versionOptions
    } = this.state;
    const rowSelection = {selectedRowKeys, onChange: this.onSelectChange};
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14},
    };
    const uploadButton = (
      <div>
        <Button>
          <Icon type="upload"/> 上传.zip文件
        </Button>
      </div>
    );
    const upload_headers = {
      'Authorization': 'Bearer ' + configureStore.store.getState().main.authToken.access_token
    };
    return (
      <div>
        <BasicInfo
          infoList={infoList}
          infoData={infoData}
          isHideEditBtn={false}
          handleEdit={() => {this.setState({visible: true})}}
        />
        <div style={{margin: '10px 0'}}> {messages('setting.key2069')/*适用范围*/}:
          <RadioGroup onChange={this.onRadioGroupChange} value={scope} style={{marginLeft: 20}}>
            <Radio value={true}>{messages('setting.key2070')/*全部适用*/}</Radio>
            <Radio value={false}>{messages('setting.key2071')/*部分适用*/}</Radio>
          </RadioGroup>
          {
            scope ? null :
              <div style={{display: 'inline-block'}}>
                <Button type={'primary'} style={{marginRight: 15}} onClick={this.getStaffModal}>{messages('setting.key2072')/*添加人员*/}</Button>
              </div>
          }
        </div>
        {
          scope ? null :
            <div>
              <Tabs activeKey={activeKey}>
                <TabPane key={'user'} tab={messages('setting.key1154')/*适用人员*/}></TabPane>
              </Tabs>
              <Button
                disabled={!selectedRowKeys.length}
                onClick={this.handleDelete}
                style={{marginBottom: 20}}
                type={'primary'}
                ghost> {messages('setting.key2073')/*移除*/}
              </Button>
              <ResizeTable
                dataSource={data}
                columns={columns}
                loading={loading}
                pagination={pagination}
                size={'middle'}
                rowKey={recode => {return (`{"tenantId": "${recode.tenantId}", "userId": "${recode.id}"}`)}}
                rowSelection={rowSelection}
                bordered
              />
            </div>
        }
        <div style={{margin: '20px 0px'}}>
          <a onClick={this.goSubApplicationDetail}><Icon type="rollback"/>{messages('setting.key1114')/*返回*/}</a>
        </div>
        <ListSelector
          showDetail={true}
          confirmLoading={loading}
          labelKey="fullName"
          visible={showListSelectorStaff}
          onOk={this.handleStaffListOk}
          onCancel={this.handleStaffCancel}
          selectorItem={selectorItemStaff}/>

        <Modal
          visible={visible}
          title={messages('setting.key2074')/*编辑版本*/}
          destroyOnClose={true}
          maskClosable={false}
          onCancel={this.onModalCancel}
          onOk={this.onModalOk}
          confirmLoading={loading}
          okText={messages('setting.key1079')/*保存*/}
        >
          <Form>
            <FormItem {...formItemLayout} label={messages('setting.key1096')/*状态*/}>
              {getFieldDecorator('enabled', {
                initialValue: infoData.enabled,
                valuePropName: "checked",
                rules: [{
                  required: false,
                }]
              })
              (<Switch/>)
              }
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key1026')/*应用名称*/}>
              {getFieldDecorator('name', {
                initialValue: appName,
                rules: [{
                  required: false,
                }]
              })
              (<Input placeholder={messages('common.please.input')/*请输入*/} disabled/>)
              }
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key1971')/*版本号*/}>
              {getFieldDecorator('appLevel', {
                initialValue: appLevel,
                rules: [{
                  required: false,
                }]
              })
              (<Input placeholder={messages('common.please.input')/*请输入*/} disabled/>)
              }
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key2062')/*主版本号*/}>
              {getFieldDecorator('appMainVersion', {
                initialValue: infoData.appMainVersion,
                rules: [{
                  required: true,
                  message: messages('setting.key2075')/*主版本号不能为空*/
                }]
              })
              (<Input placeholder={messages('common.please.input')/*请输入*/}/>)
              }
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key2064')/*版本描述*/}>
              <LanguageInput
                name={infoData.releaseNote}
                i18nName={infoData.i18n ? infoData.i18n.releaseNote : ""}
                isEdit={true}
                nameChange={this.i18nNameChange}
              />

            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key2063')/*操作系统*/}>
              {getFieldDecorator('platform', {
                initialValue: infoData.platform,
                rules: [{
                  required: true,
                  message: messages('setting.key2075')/*主版本号不能为空*/
                }]
              })
              (<Select placeholder={messages('setting.key1137')/*请选择*/}>
                <Option value={'iOS'}>iOS</Option>
                <Option value={'ANDROID'}>ANDROID</Option>
              </Select>)
              }
            </FormItem>
          </Form>
          <Row style={{marginBottom: 24}}>
            <Col span={6}>
              <span style={{color: 'red', marginLeft: 35}}>*</span>
              <span style={{color: 'black'}}>&nbsp;{messages('setting.key2065')/*代码资源*/}：</span>
            </Col>
            <Col span={16}>
              <Upload action={`${config.baseUrl}/api/upload/static/attachment`}
                      headers={upload_headers}
                      fileList={fileList}
                      accept={'.zip'}
                      data={{attachmentType: 'OTHER'}}
                      onChange={this.handleUploadChange}>
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
            </Col>
          </Row>
          <Form>
            <FormItem {...formItemLayout} label={messages('setting.key2061')/*强制更新*/}>
              {getFieldDecorator('mandatory', {
                initialValue: infoData.mandatory,
                rules: [{
                  required: true,
                  message: messages('setting.key2076')/*强制更新不能为空*/
                }]
              })
              (<RadioGroup>
                <Radio value={true}>{messages('setting.key1393')/*是*/}</Radio>
                <Radio value={false}>{messages('setting.key1394')/*否*/}</Radio>
              </RadioGroup>)
              }
            </FormItem>
            {/*最小版本还没做 暂时不要*/}
            {/*<FormItem {...formItemLayout}*/}
            {/*label={<span><span style={{color: 'red', display: this.props.form.getFieldValue('mandatory') ? 'none' : 'inline'}}>*</span>&nbsp;最小版本</span>}>*/}
            {/*{getFieldDecorator('minUpdateVersion', {*/}
            {/*initialValue: infoData.minUpdateVersion,*/}
            {/*rules: [*/}
            {/*{*/}
            {/*pattern: /^[0-9]/,*/}
            {/*message: '请输入正整数',*/}
            {/*},*/}
            {/*{*/}
            {/*required: false,*/}
            {/*}*/}
            {/*]*/}
            {/*})*/}
            {/*(*/}
            {/*<Select showSearch={true}*/}
            {/*allowClear={true}*/}
            {/*optionFilterProp="children"*/}
            {/*placeholder={messages('common.please.select')}*/}
            {/*getPopupContainer={triggerNode => triggerNode.parentNode}>*/}
            {/*{this.state.versionOptions.map((item, index) => {*/}
            {/*return <Option key={index} value={item}>{item}</Option>*/}
            {/*})}*/}
            {/*</Select>*/}
            {/*)*/}
            {/*}*/}
            {/*</FormItem>*/}
          </Form>
        </Modal>
      </div>
    )
  }
}

SubApplicationVersionRecordDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

const WrappedSubApplicationVersionRecordDetail = Form.create()(SubApplicationVersionRecordDetail);
export default connect(mapStateToProps)(WrappedSubApplicationVersionRecordDetail);
